//
//  XJFlexibleParallaxView.m
//  TabelibleScrollerViewSample
//
//  Created by chenxinju on 16/6/19.
//  Copyright © 2016年 Innovation. All rights reserved.
//

#import "XJFlexibleParallaxView.h"

static const CGFloat kFlexibleWeight = 0.7;
@interface XJFlexibleParallaxView ()<UIScrollViewDelegate>

@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, assign) CGRect defaultTopViewRect;


@end
@implementation XJFlexibleParallaxView

- (instancetype)initWithFrame:(CGRect)frame topView:(UIView *)topView {
    if (self = [super initWithFrame:frame]) {
        _topView = topView;
        [self addSubview:_topView];
        
        _scrollView = [[UIScrollView alloc]initWithFrame:frame];
        _scrollView.delegate = self;
        [self addSubView:_scrollView];
        self.defaultTopViewRect = _topView.frame;
    }
    return self;

}

#pragma mark -  UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    self.contentOffset = scrollView.contentOffset;
    if ([_delegate respondsToSelector:@selector(flexibleParallaxViewDidScroll:)]) {
        [self.delegate flexibleParallaxViewDidScroll:self];
    }
      //向下拉时
    if (scrollView.contentOffset.y < 0) {
        CGFloat offsetY = - scrollView.contentOffset.y;
        CGFloat oldH = self.defaultTopViewRect.size.height;
        CGFloat oldW = self.defaultTopViewRect.size.width;
        
        CGFloat newH = oldH + offsetY;
        CGFloat newW = oldW * (newH / oldH);
        
        self.topView.frame = CGRectMake(0,0 ,newW, newH);
        self.topView.center = CGPointMake(self.center.x, self.topView.center.y);
    }else {
        //向上
      CGFloat offsetY = scrollView.contentOffset.y;
        if (offsetY > self.topView.height) {
            if ([_delegate respondsToSelector:@selector(flexibleParallaxViewDidScrollToTop:)]) {
                [self.delegate flexibleParallaxViewDidScrollToTop:self];
            }
            
        }else {
            if ([_delegate respondsToSelector:@selector(flexibleParallaxViewDidScrollFRomTop:)]) {
                [self.delegate flexibleParallaxViewDidScrollFRomTop:self];
        
          }
        }
        
        [self.topView setY:-offsetY * kFlexibleWeight ];
    
    }
}



- (void)setContentSize:(CGSize)size {
    [self.scrollView setContentSize:size];
}

- (void)addSubView:(UIView *)view {
    if (self.topView ==view || self.scrollView==view ) {
        [self addSubview:view];
    }else {
        [self.scrollView addSubview:view];
    }
}

@end
